﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace JT808Gateway.Core
{
    /// <summary>
    /// 会话管理
    /// </summary>
    public class SessionManager
    {
        /// <summary>
        /// 单例
        /// </summary>
        public static SessionManager Instance
        {
            get
            {
                lock (_lockObj)
                {
                    if (_instance == null)
                    {
                        lock (_lockObj)
                        {
                            _instance = new SessionManager();
                        }
                    }
                }
                return _instance;
            }
        }

        /// <summary>
        /// 会话列表
        /// </summary>
        public List<JT808Session> SessionList { get; private set; }

        private static SessionManager _instance = null;
        private static object _lockObj = new object();

        public SessionManager()
        {
            SessionList = new List<JT808Session>();
        }

        public void AddSession(JT808Session newSession)
        {
            lock (_lockObj)
            {
                SessionList.Add(newSession);
            }
        }

        public void RemoveSession(JT808Session session)
        {
            lock (_lockObj)
            {
                if (SessionList.IndexOf(session) != -1)
                    SessionList.Remove(session);
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="simNumber">Sim卡号</param>
        /// <param name="sendBytes">消息字节数组</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<bool> Send(string simNumber, byte[] sendBytes)
        {
            var session = SessionList.Find(u => u.SimNumber == simNumber);
            if (session != null)
            {
                await session.SendMsg(sendBytes);
                return true;
            }
            else
            {
                return false;
                throw new Exception("找不到指定Sim卡号的会话");
            }
        }
    }
}